package com.ruoyi.functiontest.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.functiontest.domain.TollMileageStatTest;
import com.ruoyi.functiontest.service.ITollMileageStatTestService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 收费里程实测数据测试Controller
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@RestController
@RequestMapping("/functiontest/TollMileageStatTest")
public class TollMileageStatTestController extends BaseController
{
    @Autowired
    private ITollMileageStatTestService tollMileageStatTestService;

    /**
     * 查询收费里程实测数据测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollMileageStatTest:list')")
    @GetMapping("/list")
    public AjaxResult list(TollMileageStatTest tollMileageStatTest)
    {
        List<TollMileageStatTest> list = tollMileageStatTestService.selectTollMileageStatTestList(tollMileageStatTest);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = tollMileageStatTest.getRoadName() != null && !tollMileageStatTest.getRoadName().isEmpty() ||
                                   tollMileageStatTest.getNodeName() != null && !tollMileageStatTest.getNodeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<TollMileageStatTest> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出收费里程实测数据测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollMileageStatTest:export')")
    @Log(title = "收费里程实测数据测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TollMileageStatTest tollMileageStatTest)
    {
        List<TollMileageStatTest> list = tollMileageStatTestService.selectTollMileageStatTestList(tollMileageStatTest);
        // 过滤出第二层数据（parentId不为0的节点）并设置路段名称
        List<TollMileageStatTest> secondLevelList = list.stream()
            .filter(item -> item.getParentId() != null && item.getParentId() != 0L)
            .map(item -> {
                // 查找父节点并设置路段名称
                if (item.getRoadName() == null || item.getRoadName().isEmpty()) {
                    list.stream()
                        .filter(parent -> parent.getId() != null && parent.getId().equals(item.getParentId()))
                        .findFirst()
                        .ifPresent(parent -> item.setRoadName(parent.getRoadName()));
                }
                return item;
            })
            .collect(Collectors.toList());
        ExcelUtil<TollMileageStatTest> util = new ExcelUtil<TollMileageStatTest>(TollMileageStatTest.class);
        util.exportExcel(response, secondLevelList, "收费里程实测数据测试数据");
    }

    /**
     * 获取收费里程实测数据测试详细信息
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollMileageStatTest:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tollMileageStatTestService.selectTollMileageStatTestById(id));
    }

    /**
     * 新增收费里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollMileageStatTest:add')")
    @Log(title = "收费里程实测数据测试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TollMileageStatTest tollMileageStatTest)
    {
        return toAjax(tollMileageStatTestService.insertTollMileageStatTest(tollMileageStatTest));
    }

    /**
     * 修改收费里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollMileageStatTest:edit')")
    @Log(title = "收费里程实测数据测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TollMileageStatTest tollMileageStatTest)
    {
        return toAjax(tollMileageStatTestService.updateTollMileageStatTest(tollMileageStatTest));
    }

    /**
     * 删除收费里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollMileageStatTest:remove')")
    @Log(title = "收费里程实测数据测试", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 检查是否可以删除节点（父节点必须在子节点删除完后才能删除）
        for (Long id : ids) {
            if (tollMileageStatTestService.hasChildById(id)) {
                return AjaxResult.error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        return toAjax(tollMileageStatTestService.deleteTollMileageStatTestByIds(ids));
    }
    
    /**
     * 实测单位批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollMileageStatTest:fieldAudit')")
    @Log(title = "收费里程实测数据测试", businessType = BusinessType.UPDATE)
    @PostMapping("/fieldAudit/batch")
    public AjaxResult fieldAuditBatch()
    {
        try {
            // 批量更新所有记录的review1字段为0
            int updatedCount = tollMileageStatTestService.updateReview1ToZero();
            System.out.println("实测单位批量审核完成，更新记录数：" + updatedCount);
            return success("实测单位批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("实测单位批量审核失败：" + e.getMessage());
            return error("实测单位批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 业主批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollMileageStatTest:ownerAudit')")
    @Log(title = "收费里程实测数据测试", businessType = BusinessType.UPDATE)
    @PostMapping("/ownerAudit/batch")
    public AjaxResult ownerAuditBatch(@RequestBody Map<String, Object> params)
    {
        try {
            Long deptId = params.get("deptId") != null ? Long.valueOf(params.get("deptId").toString()) : null;
            Long roleId = params.get("roleId") != null ? Long.valueOf(params.get("roleId").toString()) : null;
            
            System.out.println("业主批量审核 - 审核所有数据，deptId: " + deptId + ", roleId: " + roleId);
            
            // 1. 校验所有数据的review1字段是否都为0
            boolean allReview1Zero = tollMileageStatTestService.checkAllReview1IsZero();
            if (!allReview1Zero) {
                return error("业主批量审核失败：存在未通过实测单位审核的数据，请先完成实测单位审核");
            }
            
            // 2. 构建查询条件
            TollMileageStatTest queryCondition = new TollMileageStatTest();
            queryCondition.setDeptId(deptId);
            queryCondition.setRoleId(roleId);
            
            // 3. 从params中提取查询条件
            if (params.get("roadName") != null) {
                queryCondition.setRoadName(params.get("roadName").toString());
            }
            if (params.get("nodeName") != null) {
                queryCondition.setNodeName(params.get("nodeName").toString());
            }
            
            // 4. 根据条件批量更新业主审核状态
            int updatedCount = tollMileageStatTestService.updateReview2ToZeroByCondition(queryCondition);
            
            System.out.println("业主批量审核完成，更新记录数：" + updatedCount);
            return success("业主批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("业主批量审核失败：" + e.getMessage());
            return error("业主批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 中心批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollMileageStatTest:centerAudit')")
    @Log(title = "收费里程实测数据测试", businessType = BusinessType.UPDATE)
    @PostMapping("/centerAudit/batch")
    public AjaxResult centerAuditBatch()
    {
        try {
            System.out.println("中心批量审核 - 审核所有数据");
            
            // 1. 校验所有数据的review1和review2字段是否都不为空且都为0
            boolean allReview1AndReview2Zero = tollMileageStatTestService.checkAllReview1AndReview2AreZero();
            if (!allReview1AndReview2Zero) {
                return error("中心批量审核失败：存在未通过实测单位审核或业主审核的数据，请先完成前序审核");
            }
            
            // 2. 批量更新中心审核状态
            int updatedCount = tollMileageStatTestService.updateReview3ToZero();
            
            System.out.println("中心批量审核完成，更新记录数：" + updatedCount);
            return success("中心批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("中心批量审核失败：" + e.getMessage());
            return error("中心批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 构建树形结构
     */
    private List<TollMileageStatTest> buildTree(List<TollMileageStatTest> list) {
        // 构建父子关系映射
        Map<Long, TollMileageStatTest> nodeMap = new HashMap<>();
        List<TollMileageStatTest> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (TollMileageStatTest node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (TollMileageStatTest node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                TollMileageStatTest parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<TollMileageStatTest>());
                    }
                    @SuppressWarnings("unchecked")
                    List<TollMileageStatTest> children = (List<TollMileageStatTest>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }
}
